<template>
  <div class="box">
    <var-app-bar title="图库" title-position="center">
      <template #left>
        <var-button
          @click="() => $router.go(-1)"
          color="transparent"
          text-color="#fff"
          round
          text
        >
          <var-icon name="chevron-left" :size="24" />
        </var-button>
      </template>
    </var-app-bar>
    <div class="imgs" ref="imgs">
      <var-image
        v-for="item in lists"
        class="img"
        ripple
        lazy
        :src="item"
        :loading="loading"
        :error="loading"
        @click="preview(item)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'
import { getImgList } from '@/api/imgs'
import _ from 'lodash'
import loading from '@/assets/images/loading3.gif'
import { ImagePreview } from '@varlet/ui'
const $router = useRouter()
const $route = useRoute()
const imgID = ref('')
const lists: any = ref([])
const imgs: any = ref(null)
const getList = async () => {
  const obj = {
    return: 'json',
    id: imgID.value,
    num: 10,
  }
  const res = await getImgList(obj)
  lists.value = [...new Set([...lists.value, ...res.pic])]
}

// 滚动事件处理函数
const handleScroll = _.throttle(() => {
  if (imgs.value) {
    const containerHeight = imgs.value.scrollHeight
    const scrollTop = imgs.value.scrollTop
    const clientHeight = imgs.value.clientHeight
    // 计算滚动条距离底部的距离
    const scrollDistanceFromBottom =
      containerHeight - (scrollTop + clientHeight)
    if (scrollDistanceFromBottom <= 50) {
      getList()
    }
  }
}, 1000)

const preview = (src: string) => {
  ImagePreview({
    images: [src],
    closeable: true,
  })
}

onMounted(() => {
  imgID.value = $route.query.id as string
  getList()
  console.log(imgID.value)
  if (imgs.value) {
    imgs.value.addEventListener('scroll', handleScroll)
  }
})

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  if (imgs.value) {
    imgs.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped lang="scss">
.box {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .imgs {
    flex: 1;
    overflow-y: auto;
    padding: 10px 5px;

    .img {
      width: 100%;
      display: block;
      margin-bottom: 10px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    }
  }
}
</style>
